﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;

namespace CaseManagerLibrary.Encrypt
{
    public static class FileValidHelper
    {
        public static string GetFileHash(string filePath, HashAlgorithm algorithm)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] result = algorithm.ComputeHash(fs);
            algorithm.Clear();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("X"));
            }
            return sb.ToString();
        }

        public static string GetFileMD(string filePath)
        {
            string sign = "";
            try
            {
                FileStream file = new FileStream(filePath, FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retval = md5.ComputeHash(file);
                file.Close();

                StringBuilder sc = new StringBuilder();
                for (int i = 0; i < retval.Length; i++)
                {
                    sc.Append(retval[i].ToString("x2"));
                }

                sign = sc.ToString();
            }
            catch (Exception ex)
            {
            }

            return sign;
        }


        public static string GetFileSHA1(string filePath)
        {
            string sign = "";
            try
            {
                FileStream file = new FileStream(filePath, FileMode.Open);
                SHA1 sha1 = new SHA1CryptoServiceProvider();
                byte[] retval = sha1.ComputeHash(file);
                file.Close();

                StringBuilder sc = new StringBuilder();
                for (int i = 0; i < retval.Length; i++)
                {
                    sc.Append(retval[i].ToString("x2"));
                }
                sign = sc.ToString();
            }
            catch (Exception ex)
            {
            }

            return sign;
        }

        public static byte[] GetFileData(string filePath)
        {
            byte[] data = null;
            FileStream fs = null;
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                data = new byte[Convert.ToInt32(fs.Length)];
                fs.Read(data, 0, data.Length);
                fs.Close();
            }
            catch
            { }
            finally
            {
                if (fs != null)
                    fs.Dispose();
            }

            return data;
        }
    }
}
